<?php

namespace App\Http\Controllers;

use App\Libs\CommonUtils;
use App\Models\Goods;
use App\Models\Order;
use App\Models\UserTeam;
use App\Models\Volunteer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class OrderController extends Controller
{
    public function orderlist(Request $request)
    {
//        $pageNum = request()->input('current_page', 1);
//        $pageSize = request()->input('page_size', 10);
        $perPage = $request->get('perPage', 10);
        $org_id = $request->get('org_id', 0);

        $user = $request->user();

        $data = Order::with(['team_info','goods_info','user_info', 'org_info']);
        
        if($request->get('status') === '0' || $request->get('status'))
        {
            $data = $data->where('status', $request->get('status'));
        }

        $keyword = $request->get('keyword', '');
        if($user->type == 3){
            if(!empty($keyword))
            {
                $data = $data->whereHas('goods_info', function ($query) use ($keyword,$user){
                    $query->where('g_name', 'like',  "%{$keyword}%")->where('org_id',$user->org_id);
                })->orWhereHas('team_info', function ($query) use ($keyword,$user){
                    $query->where('name', 'like',  "%{$keyword}%")->where('org_id',$user->org_id);
                })->orWhereHas('user_info', function ($query) use ($keyword,$user){
                    $query->where('username', 'like',  "%{$keyword}%")->where('org_id',$user->org_id)
                        ->orwhere('phone', 'like',  "%{$keyword}%")->where('org_id',$user->org_id);
                });
            }
            $org_id = $user->org_id;
        } else if($user->type == 2){
            if(!empty($keyword))
            {
                $data = $data->whereHas('goods_info', function ($query) use ($keyword,$user){
                    $query->where('g_name', 'like',  "%{$keyword}%")->where('team_id',$user->team_id);
                })->orWhereHas('team_info', function ($query) use ($keyword,$user){
                    $query->where('name', 'like',  "%{$keyword}%")->where('team_id',$user->team_id);
                })->orWhereHas('user_info', function ($query) use ($keyword,$user){
                    $query->where('username', 'like',  "%{$keyword}%")
                        ->orwhere('phone', 'like',  "%{$keyword}%");
                });
            }
            $data = $data->where('team_id',$user->team_id);
        }else if($user->type == 4){
            if(!empty($keyword))
            {
                $data = $data->whereHas('goods_info', function ($query) use ($keyword){
                    $query->where('g_name', 'like',  "%{$keyword}%");
                })->orWhereHas('team_info', function ($query) use ($keyword){
                    $query->where('name', 'like',  "%{$keyword}%");
                })->orWhereHas('user_info', function ($query) use ($keyword){
                    $query->where('username', 'like',  "%{$keyword}%")
                        ->orwhere('phone', 'like',  "%{$keyword}%");
                });
            }
        }
        if ($org_id) {
            $data = $data->where('org_id', $org_id);
        }
//        return $data;
//
//
        $asExcel = $request->get("asExcel", false);
        $info = null;
        if($asExcel)
        {
            if($user->type===4){
                $tmp = $data->offset(1)->limit(2000)->get()->toArray();

            } else{
                $tmp = $data->get()->toArray();
            }
            $info = array(
                'data' => $tmp
            );

            $excel = Excel::create(time(),function($excel) use ($info){

                $excel->sheet('order', function($sheet) use ($info){

                    $sheet->appendRow(1, array(
                        '订单ID','订单号','商品类型','商品名称','发布团队','兑换人','联系电话','消耗积分','审核状态','兑换状态','下单时间'
                    ));

                    for ($i = 0;$i<count($info['data']);$i++){
                        $tmp = $info['data'][$i];
                        $sheet->appendRow($i+2,array(
                                $tmp["id"],$tmp["order_num"],$tmp['goods_info']['type']==0?'实物':'优惠卷',
                                $tmp['goods_info']['g_name'],$tmp['team_info']['name'],$tmp['user_info']['username'],
                                $tmp['user_info']['phone'],$tmp["points"],$tmp["status"]==0?'已通过':($tmp["status"]==1?'已拒绝':'待审核'),
                                $tmp["state"]==0?'待领取':'已领取',$tmp["updated_at"]
                            )
                        );
                    }
                });
            })->export('xls');
        }
//
//
        $data = $data->paginate($perPage)->toArray();
//        $count = $data->count();
//        $pageInfo = [
//            "current_page" => intval($pageNum),
//            "total_page" => ceil($count / $pageSize),
//            "page_size" => intval($pageSize)
//        ];

        return $this->returnJSON([
            'count' => $data['total'],
            'rows' => $data['data']
        ]);
    }

    public function pass($id)
    {
        $result = new Order();
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $order = $result->whereIn('id',  $ids)->get();

        foreach ($order as $k => $v){
            if($v['status'] != 2){
                return $this->returnJSON(null, 10002, '请选择待审核订单');
            }
        }
        $result = $result->whereIn('id',  $ids)->update(['status' => 0]);

        if ($result) {
            return $this->returnJSON(null, 0, '审核通过');
        }
        return $this->returnJSON(null, 0, '设置失败');
    }

    public function refuse(Request $request,$id)
    {
        $result = new Order();
        $volunteer = new Volunteer();
        $goods = new Goods();

        $reason = request()->input('reason');
        if (empty($reason)){
            return $this->returnJSON(null, 10003, '请填写理由');
        }
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $order = $result->whereIn('id',  $ids)->get();

        foreach ($order as $k => $v){
            if($v['status'] != 2){
                return $this->returnJSON(null, 10002, '请选择待审核订单');
            }
        }

        for($i = 0; $i < count($order); $i++)
        {
            $arr[] = $order[$i]->user_id;
            $goods_ids[] = $order[$i]->goods_id;
        }

        $result = $result->whereIn('id',  $ids)->update(['status' => 1,'reason' => $reason]);

        if ($result) {
            for($j = 0; $j < count($arr); $j++){
                $volunteer = $volunteer->where('user_id',$arr[$j])->first();
                $goods = $goods->where('id',$goods_ids[$j])->first();
                $volunteer->score = $volunteer->score+$order[$j]->points;
                $goods->g_num = $goods->g_num+1;
                $volunteer->save();
                $goods->save();
            }
            return $this->returnJSON(null, 0, '已拒绝');
        }
        return $this->returnJSON(null, 0, '设置失败');
    }

    public function take($id)
    {
        $result = new Order();
        $order = $result->where('id',  $id)->first();
        if($order->status == 2 ||$order->status == 1){
            return $this->returnJSON(null, 10002, '请确认该订单是否通过审核');
        }

        $result = $result->where('id',  $id)->update(['state' => 1, 'collect_time' => date('Y-m-d h:i:s')]);

        if ($result) {
            return $this->returnJSON($id, 0, '已领取');
        }
        return $this->returnJSON(null, 422, '设置失败');
    }


    public function orderStatistic(Request $request)
    {
        $user = $request->user();

        if ($request->has('date_range')) {
            $dateRange = array_map(function ($item) {
                return intval($item);
            }, explode(',', $request->get('date_range')));
            $begin = $dateRange[0];
            $end = $dateRange[1];
        } else {
            $begin = strtotime('-60 day');
            $end = time();
        }
        $beginDay = date('Y-m-d', $begin);
        $endDay = date('Y-m-d', $end);
//        if($user->type == 2 )
//        {
//            throw new \Exception('权限不足');
//        }

        switch ($user->type)
        {
            case 2:
                $list = DB::table(DB::raw('`order` as t1'))->selectRaw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\')  as day, count(0) as ct, (select count(0) from `order` as t2 where state = 1 and team_id ='.strval($user->team_id).'  and  DATE_FORMAT(t2.created_at,\'%Y-%m-%d\')<=DATE_FORMAT(t1.created_at,\'%Y-%m-%d\')) as total ')->whereraw("state = 1 and team_id = {$user->team_id} and DATE_FORMAT(t1.created_at,'%Y-%m-%d') >= '{$beginDay}' and DATE_FORMAT(t1.created_at,'%Y-%m-%d') <= '{$endDay}'")->groupby(DB::raw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\') '))->get();
                break;
            case 3:
                $list = DB::table(DB::raw('`order` as t1'))->selectRaw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\')  as day, count(0) as ct, (select count(0) from `order` as t2 where state = 1 and org_id ='.strval($user->org_id).'  and  DATE_FORMAT(t2.created_at,\'%Y-%m-%d\')<=DATE_FORMAT(t1.created_at,\'%Y-%m-%d\')) as total ')->whereraw("state = 1 and org_id = {$user->org_id} and DATE_FORMAT(t1.created_at,'%Y-%m-%d') >= '{$beginDay}' and DATE_FORMAT(t1.created_at,'%Y-%m-%d') <= '{$endDay}'")->groupby(DB::raw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\') '))->get();
                break;

            case 4:
                $list = DB::table(DB::raw('`order` as t1'))->selectRaw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\')  as day, count(0) as ct, (select count(0) from `order` as t2 where state = 1 and  DATE_FORMAT(t2.created_at, \'%Y-%m-%d\') <= DATE_FORMAT(t1.created_at, \'%Y-%m-%d\')) as total')->whereraw("state = 1 and DATE_FORMAT(t1.created_at,'%Y-%m-%d') >= '{$beginDay}' and DATE_FORMAT(t1.created_at,'%Y-%m-%d') <= '{$endDay}'")->groupby(DB::raw('DATE_FORMAT(t1.created_at,\'%Y-%m-%d\') '))->get();
//                dd($list);
                break;
        }

        $dayCount  = [];
        if (count($list)) {
            foreach ($list as $value) {
                $dayCount[$value->day] = [
                    'day' => $value->day,
                    'ct' => $value->ct,
                    'total' => $value->total,
                ];
            }
        }

        $begin = strtotime($beginDay);
        $end = strtotime($endDay);
//        dd($begin, $end);
        if($begin && $end) {
            for ($i = $begin; $i <= $end; $i = $i + 86400) {
                $day = date('Y-m-d', $i);

                if (!isset($dayCount[$day])) {
                    if (count($list) <= 0) {
                        $dayCount[$day] = [
                            'day' => 0,
                            'ct' => 0,
                            'total' => 0,
                        ];
                        continue;

                    }
                    if ($i == $begin) {
                        $dayCount[$day] = [
                            'day' => $day,
                            'ct' => 0,
                            'total' => $list['0']->total - $list['0']->ct,
                        ];
                    } else {
                        $pre = date('Y-m-d', $i - 86400);

                        $dayCount[$day] = [
                            'day' => $day,
                            'ct' => 0,
                            'total' => $dayCount[$pre]['total'],
                        ];
                    }
                }
            }
        }
        ksort($dayCount);

        $addData = [];
        $totalData = [];
        $dateRange = [];

        foreach ($dayCount as $item) {
            array_push($addData, $item['ct']);
            array_push($totalData, $item['total']);
            array_push($dateRange, $item['day']);
        }

        $data['day_reward_count'] = $dayCount;
        $chart = new CommonUtils();
        $data = $chart->userIncreaseChartConfig($dateRange, $addData, $totalData, ['新增订单数', '累计订单数']);
        return $this->returnJSON($data, 0, '');
    }

    public function currentOrderNum(Request $request)
    {
        $user = $request->user();

        switch ($user->type) {
            case 2:
                $teamUserIds = $this->_getTeamUserId($user->team_id);
                $data['total_order'] = Order::where('state', '=',1)->whereRaw("team_id in ({$teamUserIds})")->count();
                $data['yesterday_order'] = Order::where('state', '=',  1)->whereRaw("team_id in ({$teamUserIds})")->where('created_at', 'like', date('Y-m-d', time() - 86400))->count();
                break;
            case 3:
                $data['total_order'] = Order::where('state', '=',1)->where('org_id', $user->org_id)->count();
                $data['yesterday_order'] = Order::where('state', '=',  1)->where('org_id', $user->org_id)->where('created_at', 'like', date('Y-m-d', time() - 86400))->count();
                break;
            case 4:
                $data['total_order'] = Order::where('state', '=',1)->count();
                $data['yesterday_order'] = Order::where('state', '=',  1)->where('created_at', 'like', date('Y-m-d', time() - 86400))->count();
                break;
        }
        return $this->returnJSON($data, 0, '');

    }

    private function _getTeamUserId($teamId)
    {
        $node = UserTeam::where('team_id', $teamId)->where('verify_status', 1)->selectRaw('GROUP_CONCAT( user_id) as ids')->first();

        return $node->ids;
    }
}